<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>API Test</title>
    <style>
        .category {font-weight: bold; background-color:rgb(176, 176, 176)}
        table {width: 100%}
        th {color:white; background-color:black}
        tr:nth-child(odd) {background-color:rgb(235,235,235)}
        .apis {display:flex; flex-direction: column; flex-wrap: nowrap;
                border: solid 1px black; overflow-y:scroll; height:400px}
        .api {color: blue; cursor: pointer}
        .api:hover {background-color: blue; color: yellow}
        .param  {color: brown}
        .submit {background-color:rgb(210,210,210); position:relative; float: right}
        #result {width: 300px; height: 500px}

        .plane {display:flex; flex-direction: column; height:100%}
        .msg {padding-top:5px; padding-right:5px; overflow-y:scroll;
              border: solid 1px black}
        textarea {height: 400px; width: 100%}

    </style>
    <script src="js/jquery-1.11.3.min.js"></script>
</head>
<body>
    <div class="plane">
        <div id="apis" class="apis">
        </div>
        <div class="msg">
            <textarea id="msg" placeholder="显示API调用的结果">
            </textarea>
        </div>
    </div>

<script>
    apis = [
        //--------------------------------------------------------------------------
        {name: '照相机'},
        {name: '所有相机', api: '/api/camera/get_cameras',
                            params:{}},
        {name: '颗粒'},
        {name: '最后一组', api: '/api/particles/get_last_distribute',
                            params:{
                                camera_id: {default: "1"}
                            }},
        {name: '下载图片', api: '/api/particles/download_img',
                            returnType: "image",
                            params:{
                                img_id: {}
                            }},
        {name: '查询', api: '/api/particles/query',
                            params:{
                                camera_id: {default: "1"},
                                start: {},
                                end: {},
                                limit: {default: '500'}
                            }},
        {name: '图片'},
        {name: '手工上传图片', api: '/api/image/upload_img',
                            params:{
                                image: {type: "file"},
                            }},

        {name: '获取手工上传的图片', api: '/api/image/download_img',
                            returnType: "image",
                            params: {
                                cache_id: {},
                                ext: {default: "jpg"}
                            }},
        {name: '检测手工上传的图片', api: '/api/image/detect_img',
                            params: {
                                cache_id: {}
                            }},
        {name: '检测手工上传的图片并保存结果', api: '/api/image/save_img',
                            params: {
                                camera_id: {default: "1"},
                                cache_id: {}
                            }},
        {name: "DB"},
        {name: "清空数据", api: '/api/db/clear',
                            params: {
                                password: {}
                            }},
        {name: "Select", api: '/api/db/select',
                            params: {
                                sql: {default: "select * from "},
                            }},
        {name: "Execute", api: '/api/db/execute',
                            params: {
                                sql: {default: "update "},
                            }},
        {name: "Insert", api: '/api/db/insert',
                            params: {
                                sql: {default: "insert into "},
                            }},
        {name: "系统（暂未实现）"},
        {name: "关于", api: '/api/business/about',
                            params: {
                            }},
        {name: "磁盘使用情况", api: '/api/business/disk_usage',
                            params: {
                            }}
    ];

    function get_params(params) {
        if(params == null)
            return "&nbsp;";
        ps = '';
        for(p in params) {
            var name = params[p].name;
            if(name == null)
                name = p;
            ps += name + '、';
        }
        if(ps.length > 0)
            ps = ps.substring(0, ps.length-1);
        return ps;
    }

    function get_method(a) {
        for(p in a.params) {
            par = a.params[p];
            if(par.type != null && par.type == 'file')
                return 'post" enctype="multipart/form-data';
        }
        return 'get';
    }

    function get_form(a, i) {
        f = '<form target="_blank" action="' + a.api + '" method="' + get_method(a)
            + '" id="frm' + i + '" returnType="' + (a.returnType==null ? 'json' : a.returnType) + '">';
        for(p in a.params) {
            param = a.params[p]
            var name = param.name;
            if(name == null)
                name = p;
            f += '<span class="param">' + p + '</span>: <input name="' + name + '"';
            if(param.type != null)
                f += ' type="' + param.type + '"';
            if(param.default != null)
                f += ' value="' + param.default + '"';
            if(param.multiple != null)
                f += ' multiple="' + param.multiple + '"';
            f += '>&nbsp;';
        }
        f += '<input type="hidden" class="randomParam" name="_TtzZ_">';
        f += '<input type="button" class="submit" value="测试' + a.api + '">';
        return f + '</form>';
    }

    myHtml = "<table border='1' cellspacing='0'><tr><th>API name</th><th>API</th><th>Parameters</th></tr>";
    for(i = 0; i < apis.length; i++) {
        a = apis[i]
        if(a.api == null) {
            myHtml += '<tr><td colspan="3"><div class="category">' + a.name + '</div>';
        } else {
            myHtml += '<tr><td>' + a.name + '</td><td>';
            myHtml += '<div>' + a.api + '</div></td><td>';
            // myHtml += get_params(a.params);
            // myHtml += '</td><td>'
            myHtml += get_form(a, i);
        }
        myHtml += '</td></tr>';
    }
    myHtml += "</table>";
    $("#apis").html(myHtml);

    $(".submit").click(function(){
        $(".randomParam").val(Math.random());
        frm = $(this).parents("form");
        frmElm = document.getElementById(frm.attr("id"));
        if(frm.attr("returnType") != "json") {
            frmElm.submit();
            return;
        }

        frmData = new FormData(frmElm);
        // $("#result").text("calling " + frm.attr("action"));
        $("#msg").val("Running...");
        $.ajax({
            type: "POST",
            url: frm.attr("action"),
            data: frmData,
            processData: false,
            contentType: false,
            success: function(result) {
                my_handle(result);
            },
            error: function(e) {
                $("#msg").val("Error!");
                alert("异常: " + e);
            }
        });
    });

    function my_handle(result) {
        var color, value;
        if(result == null) {
            color = "black";
            value = '&lt;Null&gt;';
        } else if(result.err_code == 0) {
            color = "black";
            value = JSON.stringify(result);
        } else {
            color = "red";
            value = result.err_msg;
        }
        $("#msg").css("color", color);
        $("#msg").val(value);
    }


</script>
</body>
</html>